package handlers

import (
	"github.com/rs/xid"
	"github.com/shugen/models"
	"github.com/shugen/utils"
	"net/http"
	"strconv"
	"time"
)

//insert 神，星，门位
func (c *Controller) ISelf(w http.ResponseWriter, r *http.Request) {

	if r.Method != "POST" {
		return
	}
	number, _ := strconv.Atoi(r.PostFormValue("number"))
	self := &models.Self{
		SelfId:      []byte(xid.New().String()),
		Type:        r.PostFormValue("type"),
		PhoneNumber: number,
		Title:       r.PostFormValue("title"),
		Desc:        r.PostFormValue("desc"),
		Status:      1,
		CreatedAt:   time.Now().UTC(),
		UpdatedAt:   time.Now().UTC(),
	}
	if err := c.Svc.InsertSelf(self); err != nil {
		w.Write(utils.Fail(err))
		return
	}
	w.Write(utils.Success(self))

}

//update 神，星，门位
func (c *Controller) USelf(w http.ResponseWriter, r *http.Request) {

	number, _ := strconv.Atoi(r.PostFormValue("number"))
	self := &models.Self{
		SelfId: []byte(r.PostFormValue("SelfId")),
		//Type:        "",
		PhoneNumber: number,
		Title:       r.PostFormValue("title"),
		Desc:        r.PostFormValue("desc"),
		Status:      0,
		//CreatedAt: time.Time{},
		UpdatedAt: time.Now().UTC(),
	}

	ss, err := c.Svc.UpdateSelf(self)

	if err != nil {
		w.Write(utils.Fail(err))
		return
	}
	w.Write(utils.Success(ss))
}

//select 神，星，门位
func (c *Controller) SSelf(w http.ResponseWriter, r *http.Request) {

	self, err := c.Svc.SelectSelf(&models.Self{SelfId: []byte(r.PostFormValue("SelfId"))})

	if err != nil {
		w.Write(utils.Fail(err))
		return
	}
	w.Write(utils.Success(self))
}

//select List 神，星，门位
func (c *Controller) LSelf(w http.ResponseWriter, r *http.Request) {

	self, err := c.Svc.ListSelf(&models.Self{Type: r.PostFormValue("type")})

	if err != nil {
		w.Write(utils.Fail(err))
		return
	}
	w.Write(utils.Success(self))
}
